<script setup>
import { deleteComment, postAddThumbs, postCancelThumbs } from '@/axios/api/posts'
import PostMaster from '@/components/PostMaster.vue'
import UserAvatar from '@/components/UserAvatar/UserAvatar.vue'
import LfButton from '@/components/commonUI/LfButton.vue'
import LfDropdownPanel from '@/components/commonUI/LfDropdownPanel.vue'
import CommentLineIcon from '@/components/svgComponents/CommentLineIcon.vue'
import LikeIcon from '@/components/svgComponents/LikeIcon.vue'
import LikeLineIcon from '@/components/svgComponents/LikeLineIcon.vue'
import { usePostCommentQuery, useRemainCommentQuery } from '@/composables/usePostDataQuery'
import { getDateTimeStr } from '@/utils/transIUtils'
import { useQueryClient } from '@tanstack/vue-query'
import dayjs from 'dayjs'
import { computed } from 'vue'
import { usePostDetailStore } from '../postDetailStore'
import { formatText } from '@/utils/transIUtils'
import {  MoreFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatTime } from '@/utils/transIUtils'

const emit = defineEmits(['refreshUpdate'])
const props = defineProps({
  data: Object,
  isChild: Boolean,
  isLastChild: Boolean,
  postMasterUid: Number,
  postId: Number,
  isRemainChild: Boolean,
  info: Object,
})

const usernameDropdownRef = ref(null)

const handleClose = () => {
  usernameDropdownRef.value.hidePanel()
}

const isFold = ref(false)

const queryClient = useQueryClient()

const userInfo = queryClient.getQueryData(['userInfo'])


const { refetch } = usePostCommentQuery(props.postId)

const postDetailStore = usePostDetailStore()
const postId = computed(() => props.postId)

const handleDeleteComment = async () => {
   await ElMessageBox.confirm('确定要删除吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  await deleteComment(props.data.id)
  refetch()
  emit('refreshUpdate')
}

const addThumbs = () => {
  if (props.isRemainChild) {
    queryClient.setQueryData(['remainComment', props.data.pid], (oldData) => {
      return {
        ...oldData,
        result: oldData.result.map((item) => ({
          ...item,
          thumbs: item.id === props.data.id ? item.thumbs + 1 : item.thumbs,
          isThumbs: item.id === props.data.id ? !item.isThumbs : item.isThumbs,
        })),
      }
    })
  } else {
    // 乐观更新数据
    queryClient.setQueryData(['postComment', postId.value], (oldData) => {
      return {
        ...oldData,
        pages: oldData.pages.map((page) => ({
          ...page,
          result: {
            ...page.result,
            data: page.result.data.map((item) => ({
              ...item,
              thumbs: item.id === props.data.id ? item.thumbs + 1 : item.thumbs,
              isThumbs: item.id === props.data.id ? !item.isThumbs : item.isThumbs,
              children: item.children.map((child) => ({
                ...child,
                thumbs: child.id === props.data.id ? child.thumbs + 1 : child.thumbs,
                isThumbs: child.id === props.data.id ? !child.isThumbs : child.isThumbs,
              })),
            })),
          },
        })),
      }
    })
  }

  // 发送API请求
  postAddThumbs({ id: props.data.id }).then(() => {
    emit('refreshUpdate')
  })
}

const cancelThumbs = () => {
  if (props.isRemainChild) {
    queryClient.setQueryData(['remainComment', props.data.pid], (oldData) => {
      return {
        ...oldData,
        result: oldData.result.map((item) => ({
          ...item,
          thumbs: item.id === props.data.id ? item.thumbs - 1 : item.thumbs,
          isThumbs: item.id === props.data.id ? false : item.isThumbs,
        })),
      }
    })
  } else {
    // 乐观更新数据
    queryClient.setQueryData(['postComment', postId.value], (oldData) => {
      return {
        ...oldData,
        pages: oldData.pages.map((page) => ({
          ...page,
          result: {
            ...page.result,
            data: page.result.data.map((item) => ({
              ...item,
              isThumbs: item.id === props.data.id ? false : item.isThumbs,
              thumbs: item.id === props.data.id ? item.thumbs - 1 : item.thumbs,
              children: item.children.map((child) => ({
                ...child,
                isThumbs: child.id === props.data.id ? false : child.isThumbs,
                thumbs: child.id === props.data.id ? child.thumbs - 1 : child.thumbs,
              })),
            })),
          },
        })),
      }
    })
  }

  // 发送API请求
  postCancelThumbs({ id: props.data.id }).then(() => {
    emit('refreshUpdate')
  })
}
const { data: remainCommentData, refetch: refetchRemainComment } = useRemainCommentQuery(props.data.id)

const handleShowMoreComment = () => {
  if (!isFold.value) {
    refetchRemainComment()
  } else {
    isFold.value = false
  }
}

const replyUser = () => {
  postDetailStore.setToId(props.data.id)
  postDetailStore.setToUid(props.data.userInfo.uid)
  postDetailStore.setToUserName(props.data.userInfo.username)

  if (props.isRemainChild || props.isChild) {
    postDetailStore.setToId(props.data.pid)
    postDetailStore.setToRemainPid(props.data.pid)
  }
}

const handleFold = () => {
  isFold.value = true
}

const handleUnFold = () => {
  isFold.value = false
}


const showReportDialog = ref(false)
const reportInfo = ref({
  type: '',
  id: '',
  title: '',
  content: '',
})

const handleReportSuccess = () => {
  showReportDialog.value = false
  ElMessage.success('举报已提交，我们会尽快处理')
}

const handleReport = (id) => {
  reportInfo.value.id = id
  showReportDialog.value = true
}


// {{ JSON.stringify(data?.isAdmin)  }}
// {{ JSON.stringify(data?.isAuthor)  }}

console.log('data', props.data);

</script>

<template>
  <!-- padding-bottom: 150px; -->
  <div class="" style="">
    <div
      class="flex items-start pb-[15px]"
      :class="
        isChild && !isLastChild
          ? 'ml-[19.5px] border-solid border-l-1 border-tone-4 box-border'
          : isChild
          ? 'ml-[20.5px]'
          : ''
      ">
      <!-- 连接线(弧线) -->
      <div v-if="isChild" class="w-4 h-4 border-l-1 border-b-1 border-tone-4 rounded-bl-[12px] ml-[-1px]"></div>

      <div>
        <section class="flex gap-3">
          <div>
            <UserAvatar :avatar="data.userInfo?.avatar" :userId="data.userInfo?.uid" />
            <!-- 连接线 -->
            <div class="w-10 h-full flex justify-center items-end">
              <div v-if="!isChild && data.children.length > 0" class="w-[1px] h-full bg-stone-200"></div>
            </div>
          </div>
          <div>
            <!-- name & 时间 -->
            <div class="flex items-center">
              <div class="mr-2 flex gap-1 items-center">
                <div class="font-medium text-sm">{{ data.userInfo?.username }}</div>
                <PostMaster v-if="data.userInfo?.uid === postMasterUid" />
              </div>
            </div>
            <div class="">
              <span v-if="data.toUser" class="flex gap-1">
                <span>@</span>
                <LfDropdownPanel position="bottom-left" ref="usernameDropdownRef" class="flex-shrink-0" needLogin>
                  <span class="whitespace-nowrap cursor-pointer text-[--text-b] font-medium">
                    {{ data.toUser.username }}
                  </span>

                  <template #content>
                    <UserAvatarContent :userId="data.toUser.uid" @close="handleClose" />
                  </template>
                </LfDropdownPanel>
                :
              </span>
              <span class="pb-1 select-text" v-html="formatText(data.content)"></span>
              <div>
                <el-image
                  v-if="data.img"
                  style="width: 100px; height: 100px; border-radius: 10px"
                  :src="data.img"
                  :preview-src-list="[data.img]"
                  close-on-press-escape
                  :hide-on-click-modal="true"
                  fit="cover" />
              </div>
            </div>
          </div>
        </section>

        <section class="flex gap-4 items-center text-[13px] pl-1 text-[#9499A0]">
          <div v-if="!isChild && data.children.length">
            <button v-if="!isFold" @click="handleFold" class="mr-2 pl-2">
              <img src="../imgs/fold.svg" alt="" />
            </button>
            <button v-else @click="handleUnFold" class="mr-2 pl-2">
              <img src="../imgs/unfold.svg" alt="" />
            </button>
          </div>
          <div v-else class="w-[38px]"></div>

          <div class="text-xs">{{ formatTime(dayjs(data.createTime)) }}</div>
          <!-- <div class="text-xs">{{ getDateTimeStr(dayjs(data.createTime).valueOf()) }}</div> -->
          
          <LfButton @click="data.isThumbs ? cancelThumbs() : addThumbs()" type="secondary-no-bg" size="small" needLogin>
            <LikeIcon v-if="data.isThumbs" class="w-3 like-animation" color="red" />
            <LikeLineIcon v-else class="w-3" color="#9499A0" />
            <span class="text-[--text-4]">{{ data.thumbs }}</span>
          </LfButton>

          <LfButton @click="replyUser" type="secondary-no-bg" size="small" needLogin>
            <CommentLineIcon class="w-3" color="#9499A0" />
            <span class="text-[--text-4]">评论</span>
          </LfButton>
            <!-- v-if="info?.isAdmin || info?.isAuthor || data.uid == userInfo?.result.uid" -->

          <button
            v-if="info?.isAdmin  || data.uid == userInfo?.result.uid"
            @click="handleDeleteComment"
            class="flex items-center gap-1 text-[red]">
            <span>删除</span>
          </button>
          <el-dropdown trigger="click">
            <span class="action-btn">
              <el-icon><MoreFilled /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleReport(data.id)">举报</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </section>
      </div>
    </div>

    <!-- 子评论 -->
    <section v-if="!isFold">
      <PostDetailContentCommentItem
        v-for="(item, index) in data.children"
        :isChild="true"
        :isLastChild="index === data.children.length - 1 && !(data.childrenCount > data.children.length)"
        :key="item.id"
        :postMasterUid="postMasterUid"
        :data="item"
        :info="info"
        :postId="postId" />
    </section>

    <!-- 展开剩余评论 -->
    <div v-if="!isChild && data.childrenCount > data.children.length">
      <div v-if="remainCommentData && !isFold">
        <PostDetailContentCommentItem
          v-for="(item, index) in remainCommentData.result"
          :isRemainChild="true"
          :isChild="true"
          :key="item.id"
          :isLastChild="index === remainCommentData.result.length - 1"
          :postMasterUid="postMasterUid"
          :data="item"
          :postId="postId" />
      </div>
      <div v-else class="flex items-center ml-[19px] mt-[-10px] gap-2">
        <!-- 连接线(弧线) -->
        <div class="w-4 h-4 border-l-1 border-b-1 border-tone-4 rounded-bl-[12px] ml-[0.5px]"></div>
        <a @click="handleShowMoreComment" class="text-sm mt-[15px] text-[--text-4]"
          >剩余{{ data.childrenCount - data.children.length + (isFold ? 2 : 0) }}条评论</a
        >
      </div>
    </div>

    <ReportDialog v-model="showReportDialog" :report-info="reportInfo" :type="2" @success="handleReportSuccess" />
  </div>
</template>

<style scoped lang="scss">
.like-animation {
  animation: likeScale 0.3s ease;
}

@keyframes likeScale {
  0% {
    transform: scale(0.5);
  }
  50% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(1);
  }
}
</style>
